<?php
namespace Admin\Model;
use Think\Model;
class UserModel extends Model
{
    protected $insertFields = array('username','password','repass');
    protected $updateFields = array('id','email','mobile_phone','sex','repass','password');
    protected $_validate = array(
        // array('username', 'require', '账号不能为空！', 1, 'regex', 3),
        // array('username', '1,30', '账号的值最长不能超过 30 个字符！', 1, 'length', 3),
        // array('password', 'require', '密码不能为空！', 1, 'regex', 1),
        // array('cpassword', 'password', '两次密码输入不一致！', 1, 'confirm', 3),
        // array('is_use', 'number', '是否启用 1：启用0：禁用必须是一个整数！', 2, 'regex', 3),
        // array('username', '', '账号已经存在！', 1, 'unique', 3),
    );

    public function search($pageSize = 10, $isDelete = 0)
    {
        $serch=I('get.');
        $where=array();
        //关键字查询
        if (!empty($serch['username'])){
            $username=$serch['username'];
            $where['username']=array('like',"%$username%");
        }
        //时间查询
        $start = I('get.start');
        $end = I('get.end');
        if($start && $end)
            $where['reg_time'] = array('between', array(strtotime("$start 00:00:00"), strtotime("$end 23:59:59")));
        elseif($start)
            $where['reg_time'] = array('egt', strtotime("$start 00:00:00"));
        elseif($end)
            $where['reg_time'] = array('elt', strtotime("$end 23:59:59"));
        //站点查询
        if (!empty($serch['site_id'])){
            $site_id=$serch['site_id'];
            $where['site_id']=array('eq',$site_id);
        }

        $count = M('User')->where($where)->count();
        $page = new \Think\Page($count, $pageSize,$_GET);
        // 配置翻页的样式
        $page->setConfig('prev', '&lt;&lt;');
        $page->setConfig('next', '&gt;&gt;');
        $data['page'] = $page->show();
        //获取分页数据
        $data['data'] = M('User a')->field('a.*,b.site_name')->join('left join '.C('DB_PREFIX').'site b on b.id=a.site_id')->where($where)->order('a.id DESC')->limit($page->firstRow.','.$page->listRows)->select();
        //总条数
        $data['count'] = $count;
        return $data;
    }

    protected function _before_insert(&$data, $option)
    {
        $data['password'] = md5($data['password'] . C('MD5_KEY'));
    }
    
    protected function _before_update(&$data, $option)
    { 
        // 判断密码为空就不修改这个字段
        if(empty($data['password']))
            unset($data['password']);
        else 
            $data['password'] = md5($data['password'] . C('MD5_KEY'));
    }
}